<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2017/10/30
 * Time: 15:48
 */
namespace app\api\service;
use think\Cache;
use think\Db;
require_once BASE_ROOT."core/application/common.php";
class GoodsService
{
 /**
  * 商品列表
  * @param $data
  * @param $order
  * @param $by
  * @param int $page
  * @return false|null|\PDOStatement|string|\think\Collection
  */
 private $g='ybsc_goods';
 private $c='ybsc_cart';
 private $f='ybsc_user_favorites';
 private $b='ybsc_goods_brand';
 private $i='ybsc_images';
 private $s='ybsc_goods_sku';
 private $cate='ybsc_goods_cate';
 private $a='ybsc_user_address';
 private $hd='ybsc_business_activity';
 private $dq='ybsc_area';
 private $attr='ybsc_goods_attr';
 private $spec='ybsc_goods_spec_format';
 public function getGoodsList($data,$order,$by,$page = 1)
 {
  if(isset($data['cate_id']))
  {
   //根据分类id 获取子类id
   $data['cate_id'] = ['in',self::InfiniteGoods($data['cate_id'],$data['mch_id'])];
  }
  $goods_list = null;
  //商品列表
  $goods_list = Db::name($this->g)->field("goods_id,goods_name,price,introduction,images,cate_id")
      ->where($data)
      ->where("state",1)
      ->where("is_del",0)
      ->page($page, PAGE_NUM)
      ->order($order,$by)
      ->order("sort desc,create_time desc")
      ->select();
  if(empty($goods_list))
  {
   return $goods_list;
  }
  //获取图片
  foreach ($goods_list as $k=>$value)
  {
   $pic = Db::name($this->i)->where("img_id",$value['images'])
       ->field("img_cover,img_cover_big,img_cover_mid,img_cover_small")
       ->find();// ->fetchSql(true)
   if($pic)
   {
    $goods_list[$k]['pic'] = $pic;
   }
  }
  return $goods_list;
 }
 /**
  * 获取商品详情
  * @param $data
  * @param $uid
  * @return array|false|\PDOStatement|string|\think\Model
  */
 public function getGoodsDetail($data,$uid)
 {
  //获取缓存
//        $goods_detail = Cache::get("goods:".$data['goods_id']);
//        if($goods_detail != false)
//        {
//            return $goods_detail;
//        }
  //商品点击
  Db::name($this->g)->where('goods_id', $data['goods_id'])
      ->setInc('clicks');
  //商品详情
  $goods_detail = Db::name($this->g)->where($data)
      ->where("state",1)
      ->where("is_del",0)->find();
  //商品不存在
  if(empty($goods_detail))
  {
   return null;
  }
  $shipping_fee_id = $goods_detail['shipping_fee_id'];
  if(!empty($shipping_fee_id))
  {
   $post_fee = Db::name('ybsc_express_shipping')->where(['shipping_fee_id'=>$shipping_fee_id])
       ->field('bynum_snum,bynum_sprice,bynum_xnum,bynum_xprice')
       ->find();
   $goods_detail['post_fee'] = $post_fee;
  }
  //有用户id
  if($uid != "")
  {
   //判断收藏
   $fav_c =  Db::name($this->f)->where("fav_id",$data['goods_id'])->where("uid",$uid)->find();
   if(!empty($fav_c))
   {
    $goods_detail['favorites'] = true;
   }
   else
   {
    $goods_detail['favorites'] = false;
   }
   //取出购物车数量
   $goods_detail['cart'] = Db::name($this->c)->where("buyer_id",$uid)->where("mch_id",$data['mch_id'])->sum("num");
  }
  //获取品牌
  $goods_detail['goods_brand'] = Db::name($this->b)->where("brand_id",$goods_detail->brand_id)->select();
  //获取图片
  $goods_pic=[];
  if($goods_detail['img_id_array']){
   $pic=explode(",", $goods_detail['img_id_array']);
   foreach($pic as $k=>$v){
    $goods_pic[$k]=Db::name($this->i)->field("img_cover,img_cover_big,img_cover_mid,img_cover_small")
        ->where("img_id",$v)->find();
   }
  }
//        $goods_pic = Db::name($this->i)->field("img_cover,img_cover_big,img_cover_mid,img_cover_small")
//                ->where("img_id","in",$goods_detail['img_id_array'])->select();
  $goods_detail['pic'] = $goods_pic;
  //商品sku
  $goods_detail['sku'] = Db::name($this->s)->where("goods_id",$data['goods_id'])->order('sku_id')->select();
  //sku图片
  foreach ($goods_detail['sku']  as $key=>$value)
  {
   $pic = Db::name($this->i)->where("img_id",$value['images'])
       ->field("img_cover,img_cover_big,img_cover_mid,img_cover_small")
       ->find();
//            if(!empty($pic))
//            {
//                foreach ($pic->toArray() as $k=>$v)
//                {
//                    $pic[$k] =  __IMG($v);
//                }
//            }
   $goods_detail['sku'][$key]['pic'] = $pic;
  }
  //获取商品属性
  // $goods_detail['goods_attr'] = Db::name($this->attr)->where("goods_id",$data['goods_id'])->select();
  if(!empty($goods_detail['goods_attribute'])){
   $goods_detail['goods_attr']=json_decode( $goods_detail['goods_attribute'],true);
   $attrs = array();
   $attrs_name = array();
   foreach ($goods_detail['goods_attr'] as $attr_item)
   {
    if(empty($attrs[$attr_item['attr_value_id']]))
    {
     $attrs_name[$attr_item['attr_value_id']] = $attr_item['attr_value'];
     $attrs[$attr_item['attr_value_id']] = $attr_item['attr_value_name'];
    }
    else
    {
     $attrs[$attr_item['attr_value_id']] .= ','.$attr_item['attr_value_name'];
    }
   }
   $goods_detail['goods_attr'] = array();
   foreach ($attrs as $ak => $av)
   {
    $aitem = array();
    $aitem['attr_value_id'] = $ak;
    $aitem['attr_value'] = $attrs_name[$ak];
    $aitem['attr_value_name'] = $av;
    $goods_detail['goods_attr'][] = $aitem;
   }
  }else{
   $goods_detail['goods_attr']=[];
  }
  //获取商品规格
  $goods_detail['goods_spec_format'] = json_decode($goods_detail['goods_spec_format'],true);
  //商品优惠
  $activity_info = Db::name($this->hd)
      ->where("mch_id",$data['mch_id'])
      ->order("satisfy_money","desc")
      ->where("is_use",1)
      ->where('star_time', '<', time())
      ->where('end_time', '>', time())
      ->select();
  foreach ($activity_info as $act_k=>$act_v)
  {
   //时间戳
   $activity_info[$act_k]['star_time']  = date("Y-m-d",$act_v['star_time']);
   $activity_info[$act_k]['end_time']  = date("Y-m-d",$act_v['end_time']);
   $activity_info[$act_k]['satisfy_money']  = intval($act_v['satisfy_money']);
   $activity_info[$act_k]['discount_money']  = intval($act_v['discount_money']);
  }
  $goods_detail['activity'] = $activity_info;
  //写入缓存
  // Cache::set("goods:".$data['goods_id'],$goods_detail,CACHE_TIME);
  return $goods_detail;
 }
 /**
  * 所有一级分类下商品
  * @param $mch_id
  * @return false|\PDOStatement|string|\think\Collection
  */
 public function cateGoods($mch_id)
 {
  //获取一级分类
  $cate_info = Db::name($this->cate)->where("pid",0)
      ->where('mch_id',$mch_id)
      ->order("sort asc")
      ->select();
  foreach ($cate_info as $key=>$value)
  {
   $carr = array();
   $cid = array();
   $cid[] = $value['cate_id'];
   $carr[] = $value['cate_id'];
   $second_info = Db::name($this->cate)->where(['pid'=>['in',$cid]])->where('mch_id',$mch_id)->select();
   $cid = array();
   foreach ($second_info as $citem)
   {
    $carr[] = $citem['cate_id'];
    $cid[] = $citem['cate_id'];
   }
   if(!empty($cid))
   {
    $third_info = Db::name($this->cate)->where(['pid'=>['in',$cid]])->where('mch_id',$mch_id)->select();
    $cid = array();
    foreach ($third_info as $citem2)
    {
     $carr[] = $citem2['cate_id'];
    }
   }
   //商品列表
   $goods_list= Db::name($this->g)->field("goods_id,goods_name,price,introduction,images,sales,min_buy,stock")
       ->where("cate_id",'in',$carr)
       ->where('mch_id',$mch_id)
       ->where("state",1)
       ->where("is_del",0)
       ->order("sort desc,create_time desc")
       ->select();
   if(!empty($goods_list))
   {
    foreach ($goods_list as $k1=>$g_v)
    {
     $pic = Db::name($this->i)->where("img_id",$g_v['images'])
         ->field("img_cover,img_cover_big,img_cover_mid,img_cover_small")
         ->find();
     if($pic)
     {
      $goods_list[$k1]['pic'] = $pic;
     }
    }
   }
   $cate_info[$key]['goods_list'] =$goods_list;
  }
  return $cate_info;
 }
 /**
  * 商品点击次数
  * @param $data
  * @return int|true
  */
 public function goodsClicks($data)
 {
  $rs = Db::name($this->g)->where('goods_id', $data)
      ->setInc('clicks');
  return $rs;
 }
 /**
  * 收藏添加/取消
  * @param $data
  * @return int|string
  */
 public function Favorites($data)
 {
  //检测是存在收藏
  $info = Db::name($this->f)->where($data)
      ->find();
  if(!empty($info))
  {
   //删除
   $rs = Db::name($this->f)->where($data)->delete();
   $res['status']=0;$res['rs']=$rs;
  }
  else
  {
   //添加
   $data['fav_time'] = time();
//            //商品价格 | 图片
//            $good = new Goods();
//            $price = $good->where("goods_id",$data['fav_id'])->find();
//            $data['log_price'] =$price['price'];
//            $data['goods_images'] =$price['images'];
   $rs = Db::name($this->f)->insert($data);
   $res['status']=1;$res['rs']=$rs;
  }
  return $res;
 }
 /**
  * 收藏删除
  * @param $data
  * @return int
  */
 public function delFavorites($data)
 {
  $rs = Db::name($this->f)->delete($data['log_id']);
  return $rs;
 }
 /**
  * 用户收藏列表
  * @param $data
  * @return false|null|\PDOStatement|string|\think\Collection
  */
 public function getFavorites($data,$page)
 {
  $fav_list = null;
  //商品列表
  $fav_list = Db::name($this->f)->where($data)
      ->page($page,PAGE_NUM)
      ->select();
  if(empty($fav_list))
  {
   return $fav_list;
  }
  //获取图片 | 商品
  foreach ($fav_list as $key=>$value)
  {
   //商品
   $goods_info = Db::name($this->g)->where("goods_id",$value['fav_id'])
       ->where('is_del',0)->find();
   //如果关注商品不存在
   if(empty($goods_info))
   {
    //删除
    Db::name($this->f)->delete($value['log_id']);
    unset($fav_list[$key]);
    continue;
   }
   $fav_list[$key]['goods'] = $goods_info;
   $pic = Db::name($this->i)->where("img_id",$goods_info['images'])
       ->field("img_cover,img_cover_big,img_cover_mid,img_cover_small")
       ->find();
   if($pic)
   {
//                foreach ($pic->toArray() as $k=>$v)
//                {
//                    $pic[$k] =  __IMG($v);
//                }
    $fav_list[$key]['pic'] = $pic;
   }
  }
  return $fav_list;
 }
 /**
  * 获取商品内容
  * @param $data
  * @return array|false|null|\PDOStatement|string|\think\Model
  */
 public function getGoods($data)
 {
  //检测sku是否存在
  $map=['goods_id'=>$data['goods_id'],'sku_id'=>$data['sku_id']];
  $info = Db::name($this->s)->where($map)
      ->find();
  //var_dump($info);
  if(empty($info))
  {
   return null;
  }
  //获取商品名字 | 图片 | 运费
  $info['goods'] = Db::name($this->g)->field("goods_name,images,shipping_fee_id,shipping_fee")
      ->where("goods_id",$info['goods_id'])
      ->where("is_del",0)
      ->find();
  //商品信息不存在 返回空
  if(empty($info['goods']))
  {
   return null;
  }
  $shipping_fee_id = $info['goods']['shipping_fee_id'];
  if(!empty($shipping_fee_id))
  {
   $post_fee = Db::name('ybsc_express_shipping')->where(['shipping_fee_id'=>$shipping_fee_id])
       ->field('bynum_snum,bynum_sprice,bynum_xnum,bynum_xprice')
       ->find();
   $info['post_fee'] = $post_fee;
  }
  //图片
  //sku不存在图片  用商品的
  if(empty($info->images))
  {
   $pic = Db::name($this->i)->where("img_id",$info['goods']['images'])
       ->field("img_cover,img_cover_big,img_cover_mid,img_cover_small")
       ->find();
  }
  else
  {
   $pic = Db::name($this->i)->where("img_id",$info['images'])
       ->field("img_cover,img_cover_big,img_cover_mid,img_cover_small")
       ->find();
  }
  if($pic)
  {
   $info['pic'] = $pic;
  }
  //默认地址
  $address= Db::name($this->a)->field("consigner,phone,address,area")
      ->where('uid',$data['uid'])
      ->where('is_default ',1)
      ->find();
  if(empty($address))
  {
   //不存在默认地址  取最新创建的一条
   $address= Db::name($this->a)->field("consigner,phone,address,area")
       ->where('uid',$data['uid'])
       ->order("create_time","desc")
       ->find();
  }
//        $res= Area::get($address['area']);
//        $city=Area::get($res['pid']);
//        $pro=Area::get($city['pid']);
  $res=Db::name($this->dq)->where('id',$address['area'])->find();
  $city=Db::name($this->dq)->where('id',$res['pid'])->find();
  $pro=Db::name($this->dq)->where('id',$city['pid'])->find();
  $address['province']= $pro['name'];
  $address['city']=$city['name'];
  $address['district']=$res['name'];
  $info['address']=$address;
  //满减
  $activity_info = Db::name($this->hd)
      ->where("mch_id",$data['mch_id'])
      ->where("is_use",1)
      ->order("satisfy_money","desc")
      ->where('star_time', '<', time())
      ->where('end_time', '>', time())
      ->select();
  foreach ($activity_info as $act_k=>$act_v)
  {
   //时间戳
   $activity_info[$act_k]['star_time']  = $this->__TIME($act_v['star_time']);
   $activity_info[$act_k]['end_time']  = $this->__TIME($act_v['end_time']);
  }
  $info['activity'] = $activity_info;
  return $info;
 }
 /**
  * 购物车商品信息
  * @param $data
  * @return null
  */
 public function cartGoods($data)
 {
  //检测是存在
  $data['cart_id']  = rtrim($data['cart_id'],",");
  $cart_id = explode( ',',$data['cart_id']);
  foreach ($cart_id as $key=>$value)
  {
   $cart_info = Db::name($this->c)->where('cart_id',$value)->where("buyer_id",$data['uid'])
       ->find();
   if(empty($cart_info))
   {
    continue;
   }
   //获取商品名字 | 图片 | 运费
   $cart_info['goods'] = Db::name($this->g)->field("goods_name,images,shipping_fee_id,shipping_fee")
       ->where("goods_id",$cart_info['goods_id'])
       ->where("is_del",0)
       ->find();
   //商品信息不存在 跳出
   if(empty($cart_info['goods']))
   {
    continue;
   }
   $shipping_fee_id = $cart_info['goods']['shipping_fee_id'];
   if(!empty($shipping_fee_id))
   {
    $post_fee = Db::name('ybsc_express_shipping')->where(['shipping_fee_id'=>$shipping_fee_id])
        ->field('bynum_snum,bynum_sprice,bynum_xnum,bynum_xprice')
        ->find();
    $cart_info['post_fee'] = $post_fee;
   }
   //图片
   $pic = Db::name($this->i)->where("img_id",$cart_info['goods_images'])
       ->field("img_cover,img_cover_big,img_cover_mid,img_cover_small")
       ->find();
   if($pic)
   {
    $cart_info['pic'] = $pic;
   }
   //价格
   $cart_info['price'] = Db::name($this->s)->where("sku_id",$cart_info['sku_id'])
       ->field("price,market_price,promote_price,cost_price,sku_name")
       ->find();
   $info['info'][$key] = $cart_info;
  }
  if(empty($info))
  {
   return null;
  }
  //默认地址
  $address= Db::name($this->a)->field("consigner,phone,address,area")
      ->where('uid',$data['uid'])
      ->where('is_default ',1)
      ->find();
  if(empty($address))
  {
   //不存在默认地址  取最新创建的一条
   $address= Db::name($this->a)->field("consigner,phone,address,area")
       ->where('uid',$data['uid'])
       ->order("create_time","desc")
       ->find();
  }
  $res=Db::name($this->dq)->where('id',$address['area'])->find();
  $city=Db::name($this->dq)->where('id',$res['pid'])->find();
  $pro=Db::name($this->dq)->where('id',$city['pid'])->find();
  $address['province']= $pro['name'];
  $address['city']=$city['name'];
  $address['district']=$res['name'];
  $info['address']=$address;
  //商品优惠
  $activity_info = Db::name($this->hd)
      ->where("mch_id",$data['mch_id'])
      ->order("satisfy_money","desc")
      ->where("is_use",1)
      ->where('star_time', '<', time())
      ->where('end_time', '>', time())
      ->select();
  foreach ($activity_info as $act_k=>$act_v)
  {
   //时间戳
   $activity_info[$act_k]['star_time']  = $this->__TIME($act_v['star_time']);
   $activity_info[$act_k]['end_time']  = $this->__TIME($act_v['end_time']);
  }
  $info['activity'] = $activity_info;
  return $info;
 }
 /**
  * 无限分类
  * @param $cate_id
  * @param $mch_id
  * @return array
  */
 public static  function InfiniteCate($cate_id,$mch_id)
 {
  //获取缓存
  $rs = Cache::get($mch_id."cate:".$cate_id);
  if($rs != false)
  {
   return $rs;
  }
  $rs = array();
  $cate_list = null;
  $cate_list = Db::name('ybsc_goods_cate')
      ->where("pid",$cate_id)
      ->where("mch_id",$mch_id)
      ->where("is_visible",1)
      ->order("sort asc")
      ->select();
  foreach($cate_list as $key=>$value){
   $value['cate_pic'] = self::__IMG($value['cate_pic']);
   $value['cate']= self::InfiniteCate($value['cate_id'],$mch_id);

   if(!empty($value['cate']))
   {
    $item = array();
    $item['cate_id'] = $value['cate_id'];
    $item['cate_name'] = "全部";
    $item['level'] = $value['level']+1;
    $item['cate'] = array();
    array_unshift($value['cate'],$item);
   }

   $rs[]=$value;
  }
  //写入缓存
  Cache::set($mch_id."cate:".$cate_id,$rs,CACHE_TIME);
  return $rs;
 }
 /**
  * 无限分类 根据当前分类获取所属下级分类id   用于商品类别查询
  * @param $cate_id
  * @param $mch_id
  * @return array
  */
 public static function InfiniteGoods($pid,$mch_id,$all=[],$res="")
 {
  $res.=$pid.",";
  $cate_list = Db::name('ybsc_goods_cate')->where("pid",$pid)->where("mch_id",$mch_id)->where("is_visible",1)->field("cate_id")->select();
  foreach($cate_list as $key=>$value){
   if(in_array($value["cate_id"],$all)){
    continue;
   }else {
    array_push($all,$value);
    $s=self::InfiniteGoods($value['cate_id'], $mch_id,$all).",";
    if(strlen($s)>1) {
     $res .=$s;
    }
   }
  }
  return substr($res,0,strlen($res)-1);
 }
 public function __IMG($img_path)
 {
  $path = "";
  if (! empty($img_path)) {
   if (stristr($img_path, "http://") === false && stristr($img_path, "https://") === false) {
    $path = 'http://'.$_SERVER['HTTP_HOST'] ."/". $img_path;
   } else {
    $path = $img_path;
   }
  }
  return $path;
 }
 /**
  * 时间戳转换
  * @param $time
  * @return false|string
  */
 public function __TIME($time)
 {
  $date = "";
  if (! empty($time) && $time!=0) {
   $date = date("Y-m-d H:i:s",$time) ;
  }
  return $date;
 }
}